package com.github.postsanf.yinian.activity;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.view.View;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.utils.TimeUtils;
import com.github.postsanf.yinian.utils.UIHelper;
import com.umeng.analytics.MobclickAgent;

import net.qiujuer.genius.blur.StackBlur;

import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class MicPlayActivity extends Activity implements View.OnClickListener {
    private MediaPlayer mMediaPlayer = null;
    private ImageView mic_play;
    private ImageView playmic_cover;
    private TextView timeline_audio_mic_text;
    private TextView timeline_audio_mic_texttip;
    private String Eaudio;
    private String ePeopleName;
    private String Eplace;
    boolean isComplete;
    private RelativeLayout timeline_audio;
    private TextView timeline_audio_time;
    final Html.ImageGetter imageGetter = new Html.ImageGetter() {
        public Drawable getDrawable(String source) {
            Drawable drawable = null;
            int rId = Integer.parseInt(source);
            drawable = getResources().getDrawable(rId);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
            return drawable;
        }
    };
    private int mictime;
    private int backtime;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_play_mic);
        Eaudio = getIntent().getStringExtra("Eaudio");
        ePeopleName = getIntent().getStringExtra("ePeopleName");
        Eplace = getIntent().getStringExtra("Eplace");
        initView();
    }

    public Bitmap blurBitmap(Bitmap bitmap) {
//        Bitmap outBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
//        RenderScript rs = RenderScript.create(getApplicationContext());
//        ScriptIntrinsicBlur blurScript = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
//        Allocation allIn = Allocation.createFromBitmap(rs, bitmap);
//        Allocation allOut = Allocation.createFromBitmap(rs, outBitmap);
//        blurScript.setRadius(25.0f);
//        blurScript.setInput(allIn);
//        blurScript.forEach(allOut);
//        allOut.copyTo(outBitmap);
//        bitmap.recycle();
//        rs.destroy();
        Bitmap outBitmap = StackBlur.blurNatively(bitmap, 8, false);
        return outBitmap;
    }

    private void initView() {
        mMediaPlayer = new MediaPlayer();
        mic_play = (ImageView) findViewById(R.id.mic_play);
        mic_play.setOnClickListener(this);
        findViewById(R.id.mic_play_close).setOnClickListener(this);
        playmic_cover = (ImageView) findViewById(R.id.playmic_cover);
//        Bitmap scaledBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.black_cover);
//        playmic_cover.setImageBitmap(blurBitmap(scaledBitmap));
        playmic_cover.setClickable(true);
        timeline_audio = (RelativeLayout) findViewById(R.id.timeline_audio);
        timeline_audio_time = (TextView) findViewById(R.id.timeline_audio_time);
        timeline_audio_mic_text = (TextView) findViewById(R.id.timeline_audio_mic_text);
        timeline_audio_mic_texttip = (TextView) findViewById(R.id.timeline_audio_mic_texttip);
        AlphaAnimation alphaAnimationbtns = new AlphaAnimation(0.0f, 1.0f);
        alphaAnimationbtns.setDuration(800);
        playmic_cover.startAnimation(alphaAnimationbtns);
        Animation translateAnimationf = new TranslateAnimation(0, 0, -UIHelper.dip2px(MicPlayActivity.this, 220), 0);
        translateAnimationf.setDuration(500);
//        final RotateAnimation rotateAnimationtab = new RotateAnimation(0, -4f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.ZORDER_TOP, 0.5f);
//        rotateAnimationtab.setDuration(200);
//        final RotateAnimation rotateAnimationtab2 = new RotateAnimation(-4f, 4f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.ZORDER_TOP, 0.5f);
//        rotateAnimationtab2.setDuration(400);
        timeline_audio.startAnimation(translateAnimationf);
//        translateAnimationf.setAnimationListener(new Animation.AnimationListener() {
//            @Override
//            public void onAnimationStart(Animation animation) {
//            }
//            @Override
//            public void onAnimationEnd(Animation animation) {
//                timeline_audio.startAnimation(rotateAnimationtab);
//            }
//            @Override
//            public void onAnimationRepeat(Animation animation) {
//            }
//        });
//        rotateAnimationtab.setAnimationListener(new Animation.AnimationListener() {
//            @Override
//            public void onAnimationStart(Animation animation) {
//                timeline_audio.startAnimation(rotateAnimationtab2);
//                playmic_cover.setVisibility(View.VISIBLE);
//            }
//            @Override
//            public void onAnimationEnd(Animation animation) {
//            }
//            @Override
//            public void onAnimationRepeat(Animation animation) {
//            }
//        });
        String sText1 = "";
        if (!StringUtils.isEmpty(ePeopleName)) {
            timeline_audio_mic_texttip.setText("一起留下了一段声音");
            if (!StringUtils.isEmpty(Eplace)) {
                String nametx = "";
                if (ePeopleName.length() > 3) {
                    nametx = ePeopleName + "...";
                } else {
                    nametx = ePeopleName;
                }
                String locationtx = "";
                if (Eplace.length() > 4) {
                    locationtx = Eplace + "...";
                } else {
                    locationtx = Eplace;
                }
                sText1 = "<small><font color='#666666'>" + "和 " + "</font></small>" +
                        "<font color='#333333'>" + nametx + "</font>" +
                        "<small><font color='#666666'>" + " 在 " + "</font></small>" +
                        "<img src=\"" + R.drawable.timeline_item_location2 + "\" />"
                        + "<font color='#2d47a8'>" + locationtx + "</font>";
                timeline_audio_mic_text.setText(Html.fromHtml(sText1, imageGetter, null));
            } else {
                sText1 = "<small><font color='#666666'>" + "和 " + "</font></small>" +
                        "<font color='#333333'>" + ePeopleName;
                timeline_audio_mic_text.setText(Html.fromHtml(sText1, imageGetter, null));
            }
            timeline_audio_mic_text.setVisibility(View.VISIBLE);
        } else {
            timeline_audio_mic_texttip.setText("留下了一段声音");
            if (!StringUtils.isEmpty(Eplace)) {
                sText1 = "<small><font color='#666666'>" + " 在 " + "</font></small>" +
                        "<img src=\"" + R.drawable.timeline_item_location2 + "\" />"
                        + "<font color='#2d47a8'>" + Eplace + "</font>";
                timeline_audio_mic_text.setText(Html.fromHtml(sText1, imageGetter, null));
                timeline_audio_mic_text.setVisibility(View.VISIBLE);
            } else {
                timeline_audio_mic_text.setVisibility(View.GONE);
            }
        }
        new Thread() {
            @Override
            public void run() {
                super.run();
                try {
                    mMediaPlayer.setDataSource(Eaudio);
                    mMediaPlayer.prepare();
                } catch (Exception e) {
                    e.printStackTrace();
                    return;
                }
            }
        }.start();
        mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
            @Override
            public void onPrepared(MediaPlayer mp) {
                mictime = mp.getDuration() / 1000;
                isComplete = true;
                if (mTimer != null) {
                    mTimer.cancel();
                }
                tthandler.sendEmptyMessage(2);
            }
        });
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mic_play.setImageResource(R.drawable.mic_circle_play);
                try {
                    mp.stop();
                    mp.reset();
                    mp.setDataSource(Eaudio);
                    mp.prepare();
                    if (mTimer != null)
                        mTimer.cancel();
                    tthandler.sendEmptyMessage(2);
                } catch (IOException e) {
                    e.printStackTrace();
                    return;
                }
                return;
            }
        });
    }

    @Override
    public void onBackPressed() {

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mic_play_close:
                mMediaPlayer.pause();
                mMediaPlayer.stop();
                AlphaAnimation alphaAnimationbtns = new AlphaAnimation(1.0f, 0.0f);
                alphaAnimationbtns.setDuration(500);
                playmic_cover.startAnimation(alphaAnimationbtns);
                alphaAnimationbtns.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        playmic_cover.setVisibility(View.GONE);
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
                Animation translateAnimationf = new TranslateAnimation(0, 0, 0, UIHelper.dip2px(MicPlayActivity.this, 220));
                translateAnimationf.setDuration(500);
                timeline_audio.startAnimation(translateAnimationf);
                translateAnimationf.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {
                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        timeline_audio.setVisibility(View.GONE);
                        finish();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {
                    }
                });
                break;
            case R.id.mic_play:
                if (!isComplete) {
                    Toast.makeText(MicPlayActivity.this, "加载中..", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (mMediaPlayer == null)
                    return;
                if (mMediaPlayer.isPlaying()) {
                    mic_play.setImageResource(R.drawable.mic_circle_play);
                    mMediaPlayer.stop();
                    try {
                        mMediaPlayer.prepare();//stop后下次重新播放要首先进入prepared状态
                        mMediaPlayer.seekTo(0);//须将播放时间设置到0；这样才能在下次播放是重新开始，否则会继续上次播放
                        if (mTimer != null)
                            mTimer.cancel();
                        tthandler.sendEmptyMessage(2);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    mic_play.setImageResource(R.drawable.mic_circle_over);
                    mMediaPlayer.start();
                    backtime = mictime;
                    mTimer = new Timer();
                    TimerTask mTimerTask = new TimerTask() {
                        @Override
                        public void run() {
                            tthandler.sendEmptyMessage(1);
                        }
                    };
                    mTimer.schedule(mTimerTask, 0, 1000);
                }
                break;
        }
    }

    Timer mTimer;
    Handler tthandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 1) {
                timeline_audio_time.setText(TimeUtils.secToTime(backtime--));
            } else if (msg.what == 2) {
                timeline_audio_time.setText(TimeUtils.secToTime(mictime));
            }
        }
    };

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        if (mMediaPlayer != null)
            mMediaPlayer.stop();
    }

}
